package com.example.administrator.energyida.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.example.administrator.energyida.R;
import com.example.administrator.energyida.beans.CompanyBean;
import com.example.administrator.energyida.util.OceanUtil;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

public class FormCompanyInfoActivity extends Activity {

    private AutoCompleteTextView autoCity;
    private AutoCompleteTextView autoCompanyName;
    private EditText editTextPhone;
    private Button buttonNextStep;
    private SimpleAdapter autoCityAdapter;
    private SimpleAdapter autoCompanyNameAdapter;
    private ArrayList<HashMap<String, String>> cityList = new ArrayList<>();
    private ArrayList<HashMap<String, Object>> searchList = new ArrayList<>();

    private String email;
    private String city;
    private String companyName;
    private double companyPointLat;
    private double companyPointLong;
    private String companyPhone;
    private LatLonPoint companyPoint = null;

    private String from;
    private String response;
    private String response2;
    private List<CompanyBean.ContentBean> listCompanyBeans;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_form_companyinfo);

        // 设置状态栏的颜色
        StatusBarUtil.setColor(this, Color.parseColor("#10cafd"), 50);

        initView();
        initHandler();

        //城市名自动联想
        autoCity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (count > 0) {
                    String content = s.toString().trim();
                    InputtipsQuery inputtipsQuery = new InputtipsQuery(content, null);
                    inputtipsQuery.setCityLimit(true);

                    Inputtips inputtips = new Inputtips(FormCompanyInfoActivity.this, inputtipsQuery);
                    inputtips.setInputtipsListener(new Inputtips.InputtipsListener() {
                        @Override
                        public void onGetInputtips(List<Tip> list, int i) {
                            if (i == 1000) {

                                cityList.clear();
                                for (int j = 0; j < list.size(); j++) {
                                    HashMap<String, String> hashMap = new HashMap<>();
                                    String city = list.get(j).getName();
                                    String last = city.substring(city.length() - 1, city.length());
                                    if (last.equals("市") || last.equals("县") || last.equals("区") || last.equals("旗") || last.equals("州")) {
                                        hashMap.put("city", city);
                                        cityList.add(hashMap);
                                    }

                                }

                                autoCityAdapter = new SimpleAdapter(getApplicationContext(),
                                        cityList,
                                        R.layout.item_formcompany_autocomplete,
                                        new String[]{"city"},
                                        new int[]{R.id.auto_textView_item});

                                autoCity.setAdapter(autoCityAdapter);
                                autoCityAdapter.notifyDataSetChanged();
                            }
                        }
                    });
                    inputtips.requestInputtipsAsyn();

                }
            }

            @Override
            public void afterTextChanged(Editable s) { }
        });
        autoCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                city = cityList.get(position).get("city");
                AutoCompleteTextView autoCompleteTextView = findViewById(R.id.formCompanyInfo_auto_city);
                autoCompleteTextView.setText(city);
            }
        });

        //公司名称自动联想
        autoCompanyName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String city = autoCity.getText().toString();
                if (count > 0 && city.isEmpty()==false) {
                    String content = s.toString().trim();
                    InputtipsQuery inputtipsQuery = new InputtipsQuery(content, city);
                    inputtipsQuery.setCityLimit(true);

                    Inputtips inputtips = new Inputtips(FormCompanyInfoActivity.this, inputtipsQuery);
                    inputtips.setInputtipsListener(new Inputtips.InputtipsListener() {
                        @Override
                        public void onGetInputtips(List<Tip> list, int i) {
                            if (i == 1000) {
                                searchList.clear();
                                for (int j = 0; j < list.size(); j++) {
                                    HashMap<String, Object> hashMap = new HashMap<>();
                                    String companyName = list.get(j).getName();
                                    LatLonPoint companyPoint = list.get(j).getPoint();
                                    hashMap.put("companyName", companyName);
                                    hashMap.put("companyPoint", companyPoint);
                                    searchList.add(hashMap);

                                }

                                autoCompanyNameAdapter = new SimpleAdapter(getApplicationContext(),
                                        searchList,
                                        R.layout.item_formcompany_autocomplete,
                                        new String[]{"companyName"},
                                        new int[]{R.id.auto_textView_item});

                                autoCompanyName.setAdapter(autoCompanyNameAdapter);
                                autoCompanyNameAdapter.notifyDataSetChanged();
                            }
                        }
                    });
                    inputtips.requestInputtipsAsyn();

                }
            }

            @Override
            public void afterTextChanged(Editable s) { }
        });
        autoCompanyName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String companyName = (String) searchList.get(position).get("companyName");
                companyPoint = (LatLonPoint) searchList.get(position).get("companyPoint");
                AutoCompleteTextView autoCompleteTextView = findViewById(R.id.formCompanyInfo_auto_companyName);
                autoCompleteTextView.setText(companyName);
            }
        });

        //点击下一步
        buttonNextStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (autoCity.getText().toString().isEmpty()) {
                    Toast.makeText(FormCompanyInfoActivity.this, "城市名不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (autoCompanyName.getText().toString().isEmpty() || companyPoint == null) {
                    Toast.makeText(FormCompanyInfoActivity.this, "公司名不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (editTextPhone.getText().toString().isEmpty()) {
                    Toast.makeText(FormCompanyInfoActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!isPhone(editTextPhone.getText().toString())) {
                    Toast.makeText(FormCompanyInfoActivity.this, "请填写正确手机号", Toast.LENGTH_SHORT).show();
                    return;
                }

                city = autoCity.getText().toString();
                companyPhone = editTextPhone.getText().toString();
                companyPointLat = companyPoint.getLatitude();
                companyPointLong = companyPoint.getLongitude();
                companyName = autoCompanyName.getText().toString();

                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("email", email);
                    jsonObject.put("city", city);
                    jsonObject.put("company", companyName);
                    jsonObject.put("phone", Long.parseLong(companyPhone));
                    jsonObject.put("longitude", companyPointLong);
                    jsonObject.put("latitude", companyPointLat);
                } catch (JSONException e) {
                    e.printStackTrace();
                }


                new OceanUtil("registerInfo.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                    @Override
                    public void callback(String strResponse) {
                        response = strResponse;
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                }).postInfo();
            }
        });

    }

    @SuppressLint("HandlerLeak")
    private void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    //点击下一步按钮
                    case 1:
                        if (response.contains("10010")) {
                            if (from.equals("Login")) {
                                Intent intent = new Intent();
                                intent.setClass(FormCompanyInfoActivity.this, FormFactoryInfoActivity.class);
                                startActivity(intent);
                            }
                            if (from.equals("MyInfo")) {
                                finish();
                            }

                        }
                        if (response.contains("-20010")) {
                            Toast.makeText(FormCompanyInfoActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    //来自修改信息  获取信息并显示
                    case 2:
                        if (response2.contains("10007")) {
                            Gson gsonGetCompany = new Gson();
                            CompanyBean companyBean = gsonGetCompany.fromJson(response2, CompanyBean.class);
                            listCompanyBeans = companyBean.getContent();

                            companyName = listCompanyBeans.get(0).getCompany();
                            city = listCompanyBeans.get(0).getCity();

                            autoCity.setText(listCompanyBeans.get(0).getCity());
                            autoCompanyName.setText(listCompanyBeans.get(0).getCompany());
                            editTextPhone.setText(listCompanyBeans.get(0).getPhone());
                        }
                        if (response2.contains("-20007")) {
                            Toast.makeText(FormCompanyInfoActivity.this, "获取信息失败", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }

    void initView() {
        autoCity = findViewById(R.id.formCompanyInfo_auto_city);
        autoCompanyName = findViewById(R.id.formCompanyInfo_auto_companyName);
        editTextPhone = findViewById(R.id.formCompanyInfo_editText_phone);
        buttonNextStep = findViewById(R.id.formCompanyInfo_button_nextStep);

        SharedPreferences sharedPreferences = getSharedPreferences("account",MODE_PRIVATE);
        email = sharedPreferences.getString("email", "");

        //如果来自个人信息页面，获取信息并显示
        from = getIntent().getStringExtra("from");
        if (from.equals("MyInfo")) {
            buttonNextStep.setText("提交");

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("email", email);
                jsonObject.put("mode", 1);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            new OceanUtil("getAccountAllInfo.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                @Override
                public void callback(String strResponse) {
                    response2 = strResponse;
                    Message message = new Message();
                    message.what = 2;
                    handler.sendMessage(message);
                }
            }).postInfo();
        }
    }

    //判断手机号码
    private boolean isPhone(String phone) {
        if (phone.length() != 11) {
            return false;
        }
        String s1="^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
        return Pattern.matches(s1, phone);
    }

}
